import pymysql
from pymysql.cursors import DictCursor
from utils.log_util import get_logger

logger = get_logger()

class DBUtil:
    def __init__(self, host, port, user, password, database):
        """初始化数据库连接"""
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.connection = None
        self.connect()
    
    def connect(self):
        """建立数据库连接"""
        try:
            self.connection = pymysql.connect(
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database,
                cursorclass=DictCursor,
                autocommit=True
            )
            logger.info(f"成功连接到数据库: {self.host}:{self.port}/{self.database}")
        except Exception as e:
            logger.error(f"数据库连接失败: {str(e)}")
            raise e
    
    def close(self):
        """关闭数据库连接"""
        if self.connection:
            self.connection.close()
            logger.info("数据库连接已关闭")
    
    def execute(self, sql, params=None):
        """执行SQL语句"""
        try:
            with self.connection.cursor() as cursor:
                logger.info(f"执行SQL: {sql}，参数: {params}")
                cursor.execute(sql, params)
                return cursor.rowcount
        except Exception as e:
            logger.error(f"SQL执行失败: {str(e)}")
            raise e
    
    def query_one(self, sql, params=None):
        """查询单条记录"""
        try:
            with self.connection.cursor() as cursor:
                logger.info(f"查询单条数据: {sql}，参数: {params}")
                cursor.execute(sql, params)
                return cursor.fetchone()
        except Exception as e:
            logger.error(f"查询失败: {str(e)}")
            raise e
    
    def query_all(self, sql, params=None):
        """查询多条记录"""
        try:
            with self.connection.cursor() as cursor:
                logger.info(f"查询多条数据: {sql}，参数: {params}")
                cursor.execute(sql, params)
                return cursor.fetchall()
        except Exception as e:
            logger.error(f"查询失败: {str(e)}")
            raise e
    
    def insert(self, table, data):
        """插入数据"""
        keys = ', '.join(data.keys())
        values = ', '.join(['%s'] * len(data))
        sql = f"INSERT INTO {table} ({keys}) VALUES ({values})"
        try:
            with self.connection.cursor() as cursor:
                logger.info(f"插入数据: {sql}，参数: {list(data.values())}")
                cursor.execute(sql, list(data.values()))
                return cursor.lastrowid
        except Exception as e:
            logger.error(f"插入失败: {str(e)}")
            raise e
    
    def update(self, table, data, condition):
        """更新数据"""
        set_clause = ', '.join([f"{key} = %s" for key in data.keys()])
        where_clause = ' AND '.join([f"{key} = %s" for key in condition.keys()])
        sql = f"UPDATE {table} SET {set_clause} WHERE {where_clause}"
        params = list(data.values()) + list(condition.values())
        try:
            with self.connection.cursor() as cursor:
                logger.info(f"更新数据: {sql}，参数: {params}")
                cursor.execute(sql, params)
                return cursor.rowcount
        except Exception as e:
            logger.error(f"更新失败: {str(e)}")
            raise e
    
    def delete(self, table, condition):
        """删除数据"""
        where_clause = ' AND '.join([f"{key} = %s" for key in condition.keys()])
        sql = f"DELETE FROM {table} WHERE {where_clause}"
        try:
            with self.connection.cursor() as cursor:
                logger.info(f"删除数据: {sql}，参数: {list(condition.values())}")
                cursor.execute(sql, list(condition.values()))
                return cursor.rowcount
        except Exception as e:
            logger.error(f"删除失败: {str(e)}")
            raise e